package com.fdl.service.security.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.AuthenticationException;
import org.acegisecurity.captcha.CaptchaSecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.ui.webapp.AuthenticationProcessingFilter;

import com.fdl.common.exception.security.AuthenticationCaptchaTestFailedException;
import com.fdl.common.exception.security.AuthenticationFailureCaptchaEvent;

/**
 * 
 * @description
 * @project: hb-intra
 * @Date:2010-8-4
 * @version 1.0
 * @Company: 33e9
 * @author zhangYong.huang
 */
public class AuthenticationWithCaptchaProcessingFilter extends
		AuthenticationProcessingFilter {

	protected void onPreAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException,
			IOException {

		CaptchaSecurityContext context = (CaptchaSecurityContext) SecurityContextHolder
				.getContext();
		request.getSession().setAttribute("j_username",
				request.getParameter("j_username"));
		if (!context.isHuman()) {
			AuthenticationException e = new AuthenticationCaptchaTestFailedException(
					messages
							.getMessage(
									"AuthenticationWithCaptchaProcessingFilter.captchaFail",
									"验证码错误"));
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
					obtainUsername(request), obtainPassword(request));
			setDetails(request, authRequest);

			eventPublisher.publishEvent(new AuthenticationFailureCaptchaEvent(
					authRequest, e));

			throw e;
		}
	}
}
